<template>
  <div class="card content-box">
    <div style="width: 50%">
      <el-row>
        <el-col :span="9">
          <el-input v-model="searchForm.userId" style="width: 240px" placeholder="通过用户Id搜索" />
        </el-col>
        <el-col :span="9">
          <el-input v-model="searchForm.realName" style="width: 240px" placeholder="通过用户实名搜索" />
        </el-col>
        <el-col :span="3">
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" :icon="Delete" :disabled="searched" @click="cancelSearch">取消</el-button>
        </el-col>
      </el-row>
    </div>
    <br />
    <div class="table-box">
      <ProTable
        ref="proTable"
        :columns="columns"
        :request-api="getTableList"
        :init-param="initParam"
        :data-callback="dataCallback"
        @selection-change="handleSelectionChange"
      >
        <!-- 表格 header 按钮 -->
        <template #tableHeader="">
          <el-button v-auth="'add'" type="primary" :icon="CirclePlus" @click="openDrawer('新增')">新增用户</el-button>
          <el-button type="danger" :icon="Delete" plain :disabled="selectedRowKeys.length === 0" @click="batchDelete">
            批量删除用户
          </el-button>
        </template>
        <!-- 表格操作 -->
        <template #operation="scope">
          <el-button size="small" @click="openDrawer('查看', scope.row)">查看</el-button>
          <el-button type="primary" size="small" @click="openDrawer('编辑', scope.row)">编辑</el-button>
          <el-button type="warning" size="small" @click="resetPass(scope.row)">重置密码</el-button>
          <el-button type="danger" size="small" @click="deleteAccount(scope.row)">删除</el-button>
        </template>
      </ProTable>
      <ImportExcel ref="dialogRef" />
    </div>
    <!--抽屉-->
    <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="450px" :title="`${drawerProps.title}用户`">
      <el-form
        ref="ruleFormRef"
        label-width="100px"
        label-suffix=" :"
        :rules="rules"
        :disabled="drawerProps.isView"
        :model="userForm"
        :hide-required-asterisk="drawerProps.isView"
      >
        <el-form-item label="用户实名" prop="realname">
          <el-input v-model="userForm.realName" placeholder="请填写用户实名" clearable></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请填写用户名" clearable></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password" v-if="show_password">
          <el-input v-model="userForm.password" placeholder="请填写用户密码" clearable></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请填写邮箱" clearable></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请填写电话" clearable></el-input>
        </el-form-item>
        <el-form-item label="权限" prop="role">
          <el-select v-model="userForm.role" placeholder="选择权限" size="small">
            <el-option v-for="item in roles" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="班组" prop="group">
          <el-select v-model="classForm" placeholder="选择班组" size="small">
            <el-option v-for="item in classList" :key="item.classId" :label="item.className" :value="item.classId" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="drawerVisible = false">取消</el-button>
        <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-drawer>
    <!-- 重置密码弹窗  弃用 -->
    <el-dialog v-model="edit_Password" width="40%">
      <el-form :model="passwordForm" label-width="130px" style="padding-right: 30px">
        <el-form-item label="新密码">
          <el-input v-model="passwordForm.new"></el-input>
        </el-form-item>
        <el-form-item label="重复密码">
          <el-input v-model="passwordForm.re"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="edit_Password = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, reactive, onMounted } from "vue";
import { User } from "@/api/interface";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { CirclePlus, Delete, Search } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getAllWorkerService,
  addAccountService,
  editWorkerService,
  searchWorkerService,
  editPasswordService,
  delWorkerService
} from "@/api/systemManage/user.js";
import { getAllClassService, addClassMemberService } from "@/api/systemManage/class.js";
import { userSearchService } from "@/api/systemManage/search.js";
import { useUserStore } from "@/stores/modules/user";
//重置密码重置成123456

//获取当前存储的用户信息  ——加个当前用户权限无就跳转登录
const userRole = useUserStore().userInfo.role;
//表单检验
const rules = reactive({
  username: [{ required: true, message: "请填写用户名" }],
  userId: [{ required: true, message: "请填写用户编码" }],
  realname: [{ required: true, message: "请填写用户实名" }],
  password: [{ required: true, message: "请填写用户密码" }],
  email: [{ required: true, message: "请填写邮箱" }],
  phone: [{ required: true, message: "请填写电话" }]
});

//权限数组
const roles = ref([
  {
    value: -1,
    label: ""
  }
]);

const roles_1 = ref([
  {
    value: 2,
    label: "管理员"
  },
  {
    value: 3,
    label: "工人用户"
  }
]);

const roles_2 = ref([
  {
    value: 3,
    label: "工人用户"
  }
]);

const checkRoleOption = () => {
  if (userRole === 1) {
    roles.value = roles_1.value;
  } else if (userRole === 2) {
    roles.value = roles_2.value;
  }
};

//页面加载调用
onMounted(checkRoleOption);

//抽屉显示
const drawerVisible = ref(false);
const edit_Password = ref(false);

const drawerProps = ref({
  isView: false,
  title: "",
  row: {}
});
const show_password = ref(true);

const classList = ref([
  {
    classDate: "",
    classId: -1,
    className: ""
  }
]);

interface userListItem {
  phone: string;
  classId: String | number;
  realName: string;
  realNameId: number;
  userId: number;
}

const userList = ref<[userListItem]>([
  {
    phone: "",
    classId: -1,
    realName: "",
    realNameId: -1,
    userId: -1
  }
]);

interface user {
  phone: string;
  classId: number | String;
  realName: string;
  realNameId: number;
  userId: number;
  username: string;
  email: string;
  role: number;
}

const user = ref({
  phone: "",
  classId: -1,
  realName: "",
  realNameId: "",
  userId: null,
  username: "",
  email: "",
  role: ""
});

interface userForm {
  userId: string | null;
  username: string;
  password: string | null;
  realName: string;
  email: string | null;
  phone: string | null;
  role: number | String;
  classId: number | null;
}

const userForm = ref<userForm>({
  userId: null,
  username: "",
  password: "",
  realName: "",
  email: "",
  phone: "",
  role: "",
  classId: null
});

const clearForm = () => {
  userForm.value = {
    userId: null,
    username: "",
    password: "",
    realName: "",
    email: "",
    phone: "",
    role: "",
    classId: null
  };
};

//搜索表单
const searched = ref(true);
const searchForm = ref({
  userId: "",
  realName: ""
});
const clearSearch = () => {
  searchForm.value = {
    userId: "",
    realName: ""
  };
};

const classForm = ref<number | String>("");

//api use
const getAllClass = async () => {
  let result = await getAllClassService();
  classList.value = result.data.data;
};
onMounted(getAllClass);

//显示班组名而非班组编号
const updateClassNames = () => {
  //console.log("调用转化" + classList.value);
  userList.value.forEach(user => {
    // 查找匹配的classId
    //console.log(user.classId);
    const matchedClass = classList.value.find(cls => cls.classId == user.classId);
    //console.log("matchedClass" + matchedClass);
    if (matchedClass) {
      // 如果找到匹配的classId，则更新className
      user.classId = matchedClass.className;
    } else {
      user.classId = "暂无班组";
    }
  });
};

const getAllUser = async () => {
  //console.log("之前" + classList.value);
  let result = await getAllWorkerService();
  userList.value = result.data.data;
  updateClassNames();
  //console.log("获取全部" + userList.value);
};
//onMounted(getAllUser);

const newName = ref("");
// add one class member while add a user
const addMember = async id => {
  if (classForm.value) {
    let dataObj = {
      classId: classForm.value,
      userIdList: [id]
    };
    console.log("班组" + dataObj.classId + "成员" + dataObj.userIdList);
    await addClassMemberService(dataObj);
  } else {
    console.log("未选择班组");
  }
};

const addAccount = async () => {
  let dataObj = {
    username: userForm.value.username,
    password: userForm.value.password,
    realName: userForm.value.realName,
    email: userForm.value.email,
    phone: userForm.value.phone,
    role: userForm.value.role
  };
  // 检查dataObj中的每个字段是否为空
  for (let key in dataObj) {
    if (!dataObj[key]) {
      ElMessage.warning("请填写完整信息");
      return; // 如果有空值，则返回
    }
  }

  newName.value = userForm.value.realName;
  await addAccountService(dataObj);
  await getAllUser();
  console.log("最新" + userList.value[userList.value.length - 1].userId);
  userList.value.forEach(item => {
    console.log("循环遍历" + item.userId);
    if (item.realName === newName.value) {
      addMember(item.userId);
      console.log("匹配到了");
    }
  });
  proTable.value?.getTableList();
  clearForm();
  ElMessage.success("添加成功");
};

const editAccount = async () => {
  let dataObj = {
    userId: userForm.value.userId,
    username: userForm.value.username,
    realName: userForm.value.realName,
    //password: userForm.value.password,
    email: userForm.value.email,
    phone: userForm.value.phone,
    role: userForm.value.role,
    classId: userForm.value.classId
  };
  console.log("当前数据" + dataObj.userId);
  console.log("当前数据" + dataObj.phone);
  await editWorkerService(dataObj);
  //密码
  if (userForm.value.password) {
    let dataObj2 = {
      userId: userForm.value.userId,
      newPassword: userForm.value.password
    };
    await editPasswordService(dataObj2);
  }
  //班组
  if (classForm.value) {
    let dataObj = {
      classId: classForm.value,
      userIdList: [userForm.value.userId]
    };
    console.log("班组" + dataObj.classId + "成员" + dataObj.userIdList);
    await addClassMemberService(dataObj);
  } else {
    console.log("未选择班组");
  }
  clearForm();
  proTable.value?.getTableList();
  ElMessage.success("修改成功");
};

const delAccount = async id => {
  ElMessageBox.confirm("确认删除该账号?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    let data = {
      userId: id
    };
    const res = await delWorkerService(data);
    if (res.data.code === 0) {
      ElMessage.success("删除成功");
      proTable.value?.getTableList();
    } else {
      ElMessage.error("删除失败：" + res.data.message);
    }
  });
};

const searchAccount = async id => {
  let dataObj = {
    userId: id
  };
  //console.log("进入查找信息分装接口" + dataObj.userId);
  let result = await searchWorkerService(dataObj);
  //console.log(result);
  user.value.userId = result.data.data.userId;
  user.value.username = result.data.data.username;
  user.value.email = result.data.data.email;
  user.value.realName = result.data.data.realName;
  user.value.role = result.data.data.role;
  user.value.phone = result.data.data.phone;
  user.value.classId = result.data.data.classId;
  classForm.value = result.data.data.classId;
  //console.log("调用接口后获得数据" + user.value.realName);
};

// ProTable 实例
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({ type: 1 });

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total 这些字段，可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
  return {
    list: data.data
    //total: data.total
  };
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"，获取用户列表直接这样做
const getTableList = async () => {
  if (searched.value) {
    await Promise.all([getAllClass(), getAllUser()]);
    return {
      code: 0,
      msg: "成功",
      data: {
        data: userList.value
      }
    };
  } else if (!searched.value) {
    let result = await userSearchService(searchForm.value);
    userList.value = result.data.data;
    updateClassNames();
    return {
      code: 0,
      msg: "搜索成功",
      data: {
        data: userList.value
      }
    };
  }
};

// 表格配置项
const columns = reactive<ColumnProps<User.ResUserList>[]>([
  { type: "selection", fixed: "left", width: 70 },
  {
    prop: "username",
    label: "用户名"
  },
  { prop: "realName", label: "用户实名" },
  { prop: "classId", label: "班组" },
  { prop: "phone", label: "电话" },
  { prop: "operation", label: "操作", fixed: "right", width: 330 }
]);

// 删除用户信息
const deleteAccount = async row => {
  delAccount(row.userId);
  //proTable.value?.getTableList();
};

//搜索
//搜索事件处理函数
//const handleSearch = () => {};

const selectedRowKeys = ref<number[]>([]);

// 定义 handleSelectionChange 方法
const handleSelectionChange = selectedKeys => {
  const userIds = selectedKeys.map(key => key.userId);

  // 更新 selectedRowKeys 数组
  selectedRowKeys.value = userIds;
};

//批量删除用户信息  尚存在问题
const batchDelete = async () => {
  if (selectedRowKeys.value.length === 0) {
    // 如果没有选中的项，则不做任何操作
    alert("请选择要删除的项");
    return;
  }
  try {
    // 调用API来删除选中的项
    selectedRowKeys.value.forEach(async id => {
      await delAccount(id);
    });
    // 从userList中删除这些项
    getAllUser();
    // 清空选中项
    selectedRowKeys.value = [];
  } catch (error) {
    console.error("批量删除失败:", error);
    alert("删除失败");
  }
  proTable.value?.getTableList();
};

//重置密码表单
const passwordForm = ref({
  new: "",
  re: ""
});

// 重置用户密码
const resetPass = async (row: any = null) => {
  drawerProps.value.title = "重置";
  if (row) {
    //console.log("开搜");
    searchAccount(row.userId);
  }
  console.log(row);
  let dataObj = {
    userId: row.userId,
    oldPassWord: row.password,
    newPassword: 123456
  };
  await editPasswordService(dataObj);
  ElMessage.success("密码重置成功");
};

// 打开 drawer(新增、查看、编辑)
//const drawerRef = ref<InstanceType<typeof UserDrawer> | null>(null);
const openDrawer = async (title: string, row: any = null) => {
  drawerProps.value.title = title;
  if (row) {
    //console.log("开搜" + row.userId);
    await searchAccount(row.userId);
    //console.log(user.value);
    userForm.value.userId = user.value.userId;
    userForm.value.username = user.value.username;
    userForm.value.phone = user.value.phone;
    userForm.value.email = user.value.email;
    userForm.value.role = user.value.role;
    userForm.value.realName = user.value.realName;
    userForm.value.classId = user.value.classId;
  }
  if (title === "查看") {
    show_password.value = false;
    drawerProps.value.isView = true;
  } else if (title === "新增" || title === "编辑") {
    show_password.value = true;
    if (title === "新增") {
      classForm.value = "";
      clearForm();
    }
    drawerProps.value.isView = false;
  }
  drawerVisible.value = true;
};

const handleSubmit = () => {
  console.log(drawerProps.value.title);
  if (drawerProps.value.title === "新增") {
    addAccount();
  } else if (drawerProps.value.title === "编辑") {
    editAccount();
  } else if (drawerProps.value.title === "重置") {
    if (passwordForm.value.new === passwordForm.value.re && passwordForm.value.new) {
      userForm.value.password = passwordForm.value.new;
      editAccount();
      edit_Password.value = false;
    } else {
      ElMessage.warning("前后密码不一致或密码为空，请重新输入");
      passwordForm.value.new = "";
      passwordForm.value.re = "";
    }
  }
  drawerVisible.value = false;
};

const handleSearch = async () => {
  console.log(searchForm.value.realName);
  searched.value = false;
  //getTableList();
  proTable.value?.getTableList();
};
const cancelSearch = () => {
  clearSearch();
  searched.value = true;
  proTable.value?.getTableList();
  console.log("cancel");
};
</script>
<style scoped>
.el-button {
  border-radius: 6px;
}
</style>
